package dgt;
import java.io.ByteArrayOutputStream;
import java.util.Date;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.cache.Cache;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import common.CacheSingleton;

@SuppressWarnings("serial")
public class DGTAbstractServlet extends HttpServlet {
	protected final Logger logger = Logger.getLogger(this.getClass().getPackage().getName());
	private Fetcher fetcher;
	private KmlBuilder builder;
	private Cache cache;
	public static final String DATEKEY = "DGTDate";
	public static final String KMZKEY = "DGTKmz";
	
	@Override
	public final void init() throws ServletException {
		try {
			fetcher = new Fetcher();
			builder = new KmlBuilder();
			cache = CacheSingleton.getCache();
		} catch (Exception e) {
			throw new ServletException(e);
		}
	}
	
	@SuppressWarnings("unchecked")
	protected void cacheKmz(byte[] kmz){
		cache.put(KMZKEY, kmz);
		cache.put(DATEKEY, new Date(System.currentTimeMillis()));
		logger.info("DGT KMZ updated");
	}
	
	public Date getKmzCacheDate(){
		return (Date) cache.get(DATEKEY);
	}
	
	protected byte[] getKmzFromCache(){
		return (byte[]) cache.get(KMZKEY);
	}
	
	protected byte[] grabKmz() throws Exception{
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		ZipOutputStream out = new ZipOutputStream(byteStream);
		
		out.putNextEntry(new ZipEntry("document.kml"));
		CharSequence cs = fetcher.getCharacters();
		builder.buildKml(cs, out, Fetcher.charset);
		
		out.close();
        return byteStream.toByteArray();    
	}
}
